package com.sk.sourcecircle.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.hyphenate.chat.EMConversation;
import com.sk.sourcecircle.entity.HomePageInfo;
import com.sk.sourcecircle.entity.UserInfo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by sk on 2017/12/7.
 */

public class MyUtils {

    public static boolean isSdcardExist() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    public static boolean isFormat(View view, List<EditText> editTexts) {
        for (EditText editText : editTexts) {
            if (TextUtils.isEmpty(editText.getText().toString())) {
                String tip = (String) editText.getTag();
                SnackUtils.showError(view, tip);
                return false;
            }
        }
        return true;
    }

    public static Bitmap getBitmap(String path) throws IOException {
        Bitmap bmp = null;
        try {
            URL imgUrl = new URL(path);
            //打开连接
            URLConnection con = imgUrl.openConnection();
            InputStream in = con.getInputStream();
            bmp = BitmapFactory.decodeStream(in);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bmp;
    }

    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static int getCode(Context context) {
        return (int) SPUtils.get(context, "userId", 0);
    }

    public static String getToken(Context context) {
        return (String) SPUtils.get(context, "token", "");
    }

    public static String getMobile(Context context) {
        return (String) SPUtils.get(context, "account", "");
    }

    public static UserInfo.DataBean getUser(Context context) {
        String result = (String) SPUtils.get(context, "login", "");
        Log.v("getUser", result);
        if (result != null && result.length() > 0) {
            UserInfo user = JSON.parseObject(result, UserInfo.class);
            return user.getData();
        } else {
            return null;
        }
    }

    public static HomePageInfo.DataBean.UserInfoBean getMyInfo(Context context) {
        String result = (String) SPUtils.get(context, "pageInfo", "");
        if (result != null && result.length() > 0) {
            HomePageInfo user = JSON.parseObject(result, HomePageInfo.class);
            return user.getData().getUser_info();
        } else {
            return null;
        }
    }

    public static String getPhone(Context context) {
        HomePageInfo.DataBean.UserInfoBean userInfoBean = getMyInfo(context);
        if (userInfoBean != null) {
            return userInfoBean.getPhone();
        } else {
            UserInfo.DataBean userBean = getUser(context);
            if (userBean != null) {
                return userBean.getPhone();
            } else {
                return "";
            }
        }
    }

    public static String getName(Context context) {
        HomePageInfo.DataBean.UserInfoBean userInfoBean = getMyInfo(context);
        if (userInfoBean != null) {
            return userInfoBean.getNickname();
        } else {
            UserInfo.DataBean userBean = getUser(context);
            if (userBean != null) {
                return userBean.getNickname();
            } else {
                return "";
            }
        }
    }

    public static String getHeadUrl(Context context) {
        HomePageInfo.DataBean.UserInfoBean userInfoBean = getMyInfo(context);
        if (userInfoBean != null) {
            return userInfoBean.getHead_url();
        } else {
            UserInfo.DataBean userBean = getUser(context);
            if (userBean != null) {
                return userBean.getHead_url();
            } else {
                return "";
            }
        }
    }


    /**
     * 提供精确的加法运算。
     *
     * @param v1 被加数
     * @param v2 加数
     * @return 两个参数的和
     */
    public static double add(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }

    /**
     * 提供精确的减法运算。
     *
     * @param v1 被减数
     * @param v2 减数
     * @return 两个参数的差
     */
    public static double sub(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.subtract(b2).doubleValue();
    }

    /**
     * 提供精确的乘法运算。
     *
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */
    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }

    /**
     * 提供（相对）精确的除法运算，当发生除不尽的情况时，精确到
     * 小数点以后10位，以后的数字四舍五入。
     *
     * @param v
     * @param v1 被除数
     * @param v2 除数
     * @return 两个参数的商
     */
    public static double div(double v, double v1, double v2) {
        return div(v1, v2, DEF_DIV_SCALE);
    }

    //默认除法运算精度
    private static final int DEF_DIV_SCALE = 10;


    public static LoadingDialog getLoadingDialog(Context context, boolean isCancel) {
        MyDialogLoadingFactory myLoadingFactory = new MyDialogLoadingFactory();
        LoadingDialog loadingDialog = LoadingDialog.make(context, myLoadingFactory);
        loadingDialog.setCancelable(isCancel);
        return loadingDialog;
    }


    private final static long minute = 60 * 1000;// 1分钟
    private final static long hour = 60 * minute;// 1小时
    private final static long day = 24 * hour;// 1天
    private final static long month = 31 * day;// 月
    private final static long year = 12 * month;// 年

    /**
     * 返回文字描述的日期
     *
     * @param date
     * @return
     */
    public static String getTimeFormatText(String s) {

        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = null;
        try {
            date = fmt.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (date == null) {
            return null;
        }
        long diff = new Date().getTime() - date.getTime();
        long r = 0;
        if (diff > year) {
            r = (diff / year);
            return r + "年前";
        }
        if (diff > month) {
            r = (diff / month);
            return r + "个月前";
        }
        if (diff > day) {
            r = (diff / day);
            return r + "天前";
        }
        if (diff > hour) {
            r = (diff / hour);
            return r + "个小时前";
        }
        if (diff > minute) {
            r = (diff / minute);
            return r + "分钟前";
        }
        return "刚刚";
    }

    public static String getTimeFormatText(long time) {

        String s = stampToDate(String.valueOf(time));

        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = null;
        try {
            date = fmt.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (date == null) {
            return null;
        }
        long diff = new Date().getTime() - date.getTime();
        long r = 0;
        if (diff > year) {
            r = (diff / year);
            return r + "年前";
        }
        if (diff > month) {
            r = (diff / month);
            return r + "个月前";
        }
        if (diff > day) {
            r = (diff / day);
            return r + "天前";
        }
        if (diff > hour) {
            r = (diff / hour);
            return r + "个小时前";
        }
        if (diff > minute) {
            r = (diff / minute);
            return r + "分钟前";
        }
        return "刚刚";
    }


    public static String getTimeDifference(String starTime, String endTime) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        starTime = formatter.format(curDate);

        String timeString = "";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date parse = dateFormat.parse(starTime);
            Date parse1 = dateFormat.parse(endTime);

            long diff = parse1.getTime() - parse.getTime();

            long day = diff / (24 * 60 * 60 * 1000);
            long hour = (diff / (60 * 60 * 1000) - day * 24);
            long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            long s = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
            long ms = (diff - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000
                    - min * 60 * 1000 - s * 1000);
            // System.out.println(day + "天" + hour + "小时" + min + "分" + s +
            // "秒");
            long hour1 = diff / (60 * 60 * 1000);
            String hourString = hour1 + "";
            long min1 = ((diff / (60 * 1000)) - hour1 * 60);
            timeString = day + "天" + hour + "小时" + min + "分";

        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return timeString;
    }

    public static boolean isTui(String endTime) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String nowTime = dateFormat.format(curDate);

        Date parse = null;
        Date parse1 = null;
        long diff = 0;
        try {
            parse = dateFormat.parse(nowTime);
            parse1 = dateFormat.parse(endTime);
            diff = parse1.getTime() - parse.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        long day = diff / (24 * 60 * 60 * 1000);

        return day >= 3;

    }

    public static boolean compareTwoTime(String starTime, String endString) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        starTime = formatter.format(curDate);

        boolean isDayu = false;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date parse = dateFormat.parse(starTime);
            Date parse1 = dateFormat.parse(endString);

            long diff = parse1.getTime() - parse.getTime();
            if (diff >= 0) {
                isDayu = true;
            } else {
                isDayu = false;
            }
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return isDayu;

    }

    public static String timedate(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        @SuppressWarnings("unused")
        long lcc = Long.valueOf(time);
        int i = Integer.parseInt(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;
    }

    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }


    public static EMConversation.EMConversationType getConversationType(int chatType) {
        if (chatType == 1) {
            return EMConversation.EMConversationType.Chat;
        } else if (chatType == 2) {
            return EMConversation.EMConversationType.GroupChat;
        } else {
            return EMConversation.EMConversationType.ChatRoom;
        }
    }


    public static String saveBitmap(Bitmap mBitmap) {
        File filePic;
        try {
            filePic = new File(Environment.getExternalStorageDirectory()
                    + "/logo.png");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }

    /*
* 将时间戳转换为时间
*/
    public static String stampToDate(long s) {
        String res = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(s * 1000);
        res = simpleDateFormat.format(date);
        return res;
    }

}
